//
//  CZHomeTableViewController.swift
//  weibo
//
//  Created by 丁蒙 on 16/6/23.
//  Copyright © 2016年 丁蒙. All rights reserved.
//

import UIKit

private let reuseId = "reuseId"

class CZHomeTableViewController: CZBaseTableViewController {
    
    //下拉刷新控件
    let refresh = CZRefresh()
    
    
    var statusArray:[CZStatus] = [CZStatus]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if !isLogin {
            visitorView?.setUpVisitorViewInfo(nil, title: nil)
            return
        }
        
        setTableViewInfo()
        //请求数据
        loadWeiboHomeInfo(activityView.isAnimating())
        
    }
    
    // MARK: - 设置tableView
    func setTableViewInfo() {
        // MARK - 注册cell
        tableView.registerClass(CZStatusCell.self, forCellReuseIdentifier: reuseId)
        //设置cell自动计算高度
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 200
        //设置分割线显示风格
        tableView.separatorStyle = .None
        //设置footView
        tableView.tableFooterView = activityView
        //添加下拉刷新控件
        tableView.addSubview(refresh)
        refresh.addTarget(self, action: #selector(CZHomeTableViewController.refreshAction), forControlEvents: UIControlEvents.ValueChanged)
    }
    // MARK: - 下拉刷新监听事件
    func refreshAction() {
        loadWeiboHomeInfo(activityView.isAnimating())
    }
    
    // MARK: - 懒加载控件
    private lazy var activityView: UIActivityIndicatorView = {
       let act = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        act.color = ThemeColor
        return act
    }()
    private lazy var pulldownTipLabel: UILabel = {
       let lab = UILabel(fontSize: 15, textColor: UIColor.whiteColor())
        
        lab.backgroundColor = ThemeColor
        
        lab.frame = CGRect(x: 0, y: 64 - 34, width: SCREENW, height: 34)
        
        lab.textAlignment = .Center
        
        lab.alpha = 0
        
        return lab
    }()

    
    // MARK: - Table view data source

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statusArray.count
        
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let weiboCell = tableView.dequeueReusableCellWithIdentifier(reuseId, forIndexPath: indexPath) as! CZStatusCell
        
        weiboCell.status = self.statusArray[indexPath.row]

        return weiboCell
        
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        if statusArray.count == indexPath.row + 1 && !activityView.isAnimating() {
            print(indexPath.row)
            //开始动画
            activityView.startAnimating()
            //请求数据
            loadWeiboHomeInfo(activityView.isAnimating())
        }

    }

 }

extension CZHomeTableViewController {
    // MARK - 请求微博首页数据
    func loadWeiboHomeInfo(pullUp: Bool) {
        
        var since_id: Int64 = 0
        
        var max_id: Int64 = 0
        //上拉刷新
        if pullUp {
            max_id = statusArray.last?.id ?? 0
            if max_id > 0 {
                max_id -= 1
            }
        } else {//下拉刷新
            since_id = statusArray.first?.id ?? 0
        }
        //停止动画
        endRefresh()
        
        CZNetWorkTools.sharedTools.oauthWeiboInfo(since_id, max_id: max_id, success: { (response) in
            guard let res = response?["statuses"] as? [[String: AnyObject]] else {
                print("返回数据为nil 或类型不匹配")
                return
            }
            var temArray: [CZStatus] = [CZStatus]()
            
            for dict in res {
                let status = CZStatus(dict: dict)
                temArray.append(status)
            }
            
            if pullUp {
                self.statusArray = self.statusArray + temArray
            } else {//下拉刷新
                self.statusArray = temArray + self.statusArray
                self.setPulldownTipAnimation(temArray.count)
            }
            
            self.tableView.reloadData()
            
            }) { (error) in
                print(error)
        }
        
    }
    
    // MARK: - 设置顶部提示刷新微博条数
    func setPulldownTipAnimation(count: Int) {
        if pulldownTipLabel.superview == nil {
            navigationController!.view.insertSubview(pulldownTipLabel, belowSubview: navigationController!.navigationBar)
        }
        var text = ""
        if count > 0 {
            text = "你刷新了\(count)条微博"
        } else {
            text = "没有更新的微博"
        }
        
        pulldownTipLabel.text = text
        
        UIView.animateWithDuration(0.25, animations: { 
            self.pulldownTipLabel.alpha = 1
            self.pulldownTipLabel.transform = CGAffineTransformMakeTranslation(0, 34)
            }) { (_) in
                UIView.animateWithDuration(0.25, delay: 1.5, options: [], animations: {
                    self.pulldownTipLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) in
                        self.pulldownTipLabel.alpha = 0
                })
        }
        
    }
    
    func endRefresh() {
        activityView.stopAnimating()
        refresh.endRefreshing()
    }

}
